package com.bolingcavalry.crm.taskorder.service.impl;/*
 * @Auther:Sadie
 * @Date:2025/5/12
 * @Description:
 * @VERSON:1.8
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.base.RoleEnum;
import com.base.Status;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.minio.service.MinioService;
import com.bolingcavalry.crm.product.mapper.ProductMapper;
import com.bolingcavalry.crm.productinstallinfo.mapper.ProductInstallInfoMapper;
import com.bolingcavalry.crm.receiver.mapper.ReceiverMapper;
import com.bolingcavalry.crm.recyclebin.mapper.RecyclebinMapper;
import com.bolingcavalry.crm.recyclebin.service.OrderRestoreService;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.serviceorder.mapper.ServiceOrderMapper;
import com.bolingcavalry.crm.summaryorder.mapper.ServiceSummaryOrderMapper;
import com.bolingcavalry.crm.summaryorder.service.ServiceSummaryOrderService;
import com.bolingcavalry.crm.taskorder.mapper.ConfirmationMapper;
import com.bolingcavalry.crm.taskorder.mapper.DeviceInstallInfoMapper;
import com.bolingcavalry.crm.taskorder.mapper.ReplacementPartMapper;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.taskorder.service.ConfirmationService;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.*;
import com.entity.aftersales.AfterSales;
import com.entity.receiver.Receiver;
import com.entity.recyclebin.RecycleBinOrder;
import com.entity.product.Product;
import com.entity.serviceorder.ServiceOrder;
import com.entity.summaryorder.ServiceSummaryOrder;
import com.entity.taskorder.ConfirmationOrder;
import com.entity.taskorder.ProductInstallInfo;
import com.entity.taskorder.ReplacementPart;
import com.entity.taskorder.TaskOrder;
import com.vo.ConfirmationOrderVO;
import com.vo.ProductInstallInfoVO;
import com.vo.ReplacementPartVO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.bolingcavalry.crm.utils.AUtils.getAccessToken;
import static com.bolingcavalry.crm.utils.AUtils.getFileContentAsBase64;

@Slf4j
@Service(Status.CONFIRMATION_ORDER)
public class ConfirmationServiceimpl implements ConfirmationService, OrderRestoreService {
    @Autowired
    private ConfirmationMapper confirmationMapper;
    @Autowired
    private DeviceInstallInfoMapper deviceInstallInfoMapper;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private ReplacementPartMapper replacementPartMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MinioService minioService;
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;
    @Autowired
    private ServiceSummaryOrderMapper serviceSummaryOrderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private ProductInstallInfoMapper productInstallInfoMapper;
    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private RecyclebinMapper recyclebinMapper;
    @Override
    public ResponseResult add(ConfirmationOrderDTO confirmationOrderDTO) {
        // 新增的时候需要判断是否存在上级任务单
        // 获取任务单号
        String taskOrderNumber = confirmationOrderDTO.getTaskOrderNumber();
        LambdaQueryWrapper<TaskOrder> taskOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        taskOrderLambdaQueryWrapper.eq(TaskOrder::getTaskOrderNumber, taskOrderNumber);
        TaskOrder taskOrder = taskorderMapper.selectOne(taskOrderLambdaQueryWrapper);
        if(taskOrder==null){
            return ResponseResult.error("单号不存在上级订单，请先创建任务单，或核对单号是否正确");
        }
        LambdaQueryWrapper<ConfirmationOrder> confirmationOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        confirmationOrderLambdaQueryWrapper.eq(ConfirmationOrder::getTaskOrderNumber, taskOrderNumber)
                                           .eq(ConfirmationOrder::getIsDeleted, 1);
        if(confirmationMapper.selectOne(confirmationOrderLambdaQueryWrapper)!=null){
            return ResponseResult.error("该单号已存在确认单，请勿重复添加");
        }
        // 权限检查：只有任务接收人或特定角色可以添加确认单
        String currentUsername = SecurityUtils.getCurrentUsername();
        String currentNickname = aUtils.getNickNameByuserName(currentUsername);

        // 检查是否具有特殊权限角色
        List<String> currentUserRoles = SecurityUtils.getCurrentUserRoles();
        boolean hasSpecialRole = currentUserRoles.contains(RoleEnum.TECHNICAL_COMMAND.getCode()) ||
                currentUserRoles.contains(RoleEnum.ADMIN.getCode()) ||
                currentUserRoles.contains(RoleEnum.GENERAL_COMMAND.getCode());

        // 检查是否为任务接收人
        boolean isTaskReceiver = false;
        LambdaQueryWrapper<Receiver> receiverWrapper = new LambdaQueryWrapper<>();
        receiverWrapper.eq(Receiver::getOrderNumber, taskOrderNumber);
        List<Receiver> receivers = receiverMapper.selectList(receiverWrapper);

        for (Receiver receiver : receivers) {
            String receiverNickname = aUtils.getUserNickNameByUserId(receiver.getUserId());
            if (currentNickname.equals(receiverNickname)) {
                isTaskReceiver = true;
                break;
            }
        }

        // 只有任务接收人或具有特殊权限的用户才能添加确认单
        if (!isTaskReceiver && !hasSpecialRole) {
            return ResponseResult.error("您没有权限添加该任务单的确认单");
        }

        if(aUtils.getOrderCount(confirmationOrderDTO.getTaskOrderNumber())<1){
            log.error("不存在前置单号");
            return ResponseResult.error("单号不存在前置表单，请核对单号");
        }
        ConfirmationOrder confirmationOrder = new ConfirmationOrder();
        BeanUtils.copyProperties(confirmationOrderDTO,confirmationOrder);
        //设置任务单id
        confirmationOrder.setTaskOrderId(taskorderMapper.selectIdByOrderNumber(confirmationOrderDTO.getTaskOrderNumber()));
        //根据公司id
        Long customerCompanyId = aUtils.getCustomerCompanyId(confirmationOrderDTO.getCustomerCompanyName());
        if(customerCompanyId==null)
            return ResponseResult.error("客户名称不存在，请核对客户名");
        else
        confirmationOrder.setCustomerCompanyId(customerCompanyId);
        //查询联系人id
        confirmationOrder.setContactPersonId(aUtils.getcontactPersonId(confirmationOrderDTO.getContactPersonName(), confirmationOrderDTO.getContactPersonPhone(), confirmationOrder.getCustomerCompanyId()));
        //填表人、填表时间 改为上传的时间
        confirmationOrder.setFiller(confirmationOrderDTO.getFiller());
        confirmationOrder.setFillTime(confirmationOrderDTO.getFillTime());
        //设置状态待总结？
        confirmationOrder.setStatus(Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);
        confirmationOrder.setImagesUrl(confirmationOrderDTO.getImagesUrl());
        //更新售后总括表为待总结
        LambdaQueryWrapper<AfterSales> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AfterSales::getOrderNumber,confirmationOrderDTO.getTaskOrderNumber());
        AfterSales afterSales = afterSalesMapper.selectOne(wrapper);
        afterSales.setStatus(Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);
        afterSalesMapper.updateById(afterSales);

        //设置产品现场使用信息
        ProductInstallInfoDTO productInstallInfoDto = confirmationOrderDTO.getProductUseInformation();
        ProductInstallInfo productInstallInfo = productInstallInfoMapper.selectByTakeOrderId(confirmationOrder.getTaskOrderId());

        //如果productInstallInfo不为空说明之前存在设备安装信息，同时产品名称不为空，用来校验是否传入了脏数据
        //如果都校验通过则拿到产品安装信息表的id
        // 先进行空值检查
        if (productInstallInfoDto == null) {
            throw new IllegalArgumentException("产品安装信息DTO不能为空");
        }

        // 判断是否已存在对应的ProductInstallInfo记录
        Long productInstallInfoId = null;
        if (productInstallInfo != null &&
                productInstallInfoDto.getProductName() != null &&
                !productInstallInfoDto.getProductName().isEmpty()) {
            productInstallInfoId = productInstallInfo.getId();
        }

        // 如果已存在记录，则更新
        if (productInstallInfo != null && productInstallInfoId != null) {
            // 设置安装地点
            String installationLocation = productInstallInfoDto.getInstallationLocation();
            if (installationLocation != null && !installationLocation.isEmpty()) {
                productInstallInfo.setInstallationLocation(installationLocation);
            }

            // 设置现场温度/压力
            String fieldTemperaturePressure = productInstallInfoDto.getFieldTemperaturePressure();
            if (fieldTemperaturePressure != null && !fieldTemperaturePressure.isEmpty()) {
                productInstallInfo.setFieldTemperaturePressure(fieldTemperaturePressure);
            }

            // 设置测量介质
            String measurementMedium = productInstallInfoDto.getMeasurementMedium();
            if (measurementMedium != null && !measurementMedium.isEmpty()) {
                productInstallInfo.setMeasurementMedium(measurementMedium);
            }

            // 设置自控厂家
            String controlManufacturer = productInstallInfoDto.getControlManufacturer();
            if (controlManufacturer != null && !controlManufacturer.isEmpty()) {
                productInstallInfo.setControlManufacturer(controlManufacturer);
            }

            // 前后直管段长度
            String frontAndBackPipeSegment = productInstallInfoDto.getFrontAndBackPipeSegment();
            if (frontAndBackPipeSegment != null && !frontAndBackPipeSegment.isEmpty()) {
                productInstallInfo.setFrontAndBackPipeSegment(frontAndBackPipeSegment);
            }

            // 通讯方式
            String communicationMethod = productInstallInfoDto.getCommunicationMethod();
            if (communicationMethod != null && !communicationMethod.isEmpty()) {
                productInstallInfo.setCommunicationMethod(communicationMethod);
            }

            // 其他
            String otherNotes = productInstallInfoDto.getOtherNotes();
            if (otherNotes != null && !otherNotes.isEmpty()) {
                productInstallInfo.setOtherNotes(otherNotes);
            }

            // 维修人员
            String maintenancePerson = productInstallInfoDto.getMaintenancePerson();
            if (maintenancePerson != null && !maintenancePerson.isEmpty()) {
                productInstallInfo.setMaintenancePerson(maintenancePerson);
            }

            // 保修日期
            String warrantyDate = productInstallInfoDto.getWarrantyDate();
            if (warrantyDate != null && !warrantyDate.isEmpty()) {
                productInstallInfo.setWarrantyDate(warrantyDate);
            }

            // 服务起止时间
            String servicePeriod = productInstallInfoDto.getServicePeriod();
            if (servicePeriod != null && !servicePeriod.isEmpty()) {
                productInstallInfo.setServicePeriod(servicePeriod);
            }
            productInstallInfoMapper.updateById(productInstallInfo);
        } else {
            // 不存在记录，需要创建新的记录
            // 先创建产品记录（如果产品名不为空）
            Long productId = null;
            if (productInstallInfoDto.getProductName() != null &&
                    !productInstallInfoDto.getProductName().isEmpty()) {
                //先根据传入的产品名加型号去查询对应的id
                LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productLambdaQueryWrapper.eq(Product::getName, productInstallInfoDto.getProductName());
                if (StringUtils.isNotBlank(productInstallInfoDto.getVersion())) {
                    productLambdaQueryWrapper.eq(Product::getVersion, productInstallInfoDto.getVersion());
                }
                else{
                    productLambdaQueryWrapper.isNull(Product::getVersion);
                }
                if (StringUtils.isNotBlank(productInstallInfoDto.getSpecification())) {
                    productLambdaQueryWrapper.eq(Product::getSpecification, productInstallInfoDto.getSpecification());
                }
                else{
                    productLambdaQueryWrapper.isNull(Product::getSpecification);
                }
                Product product = productMapper.selectOne(productLambdaQueryWrapper);

                if(product != null){
                    productId = product.getId();
                }
                else{
                    Product product1 = new Product();
                    product1.setName(productInstallInfoDto.getProductName());
                    product1.setVersion(productInstallInfoDto.getVersion());
                    productMapper.insert(product1);
                    productId = product1.getId();
                }
                }

            // 创建产品安装信息记录
            ProductInstallInfo newProductInstallInfo = new ProductInstallInfo();

            // 设置产品ID（如果存在）
            if (productId != null) {
                newProductInstallInfo.setProductId(productId);
            }

            // 设置安装地点
            String installationLocation = productInstallInfoDto.getInstallationLocation();
            if (installationLocation != null && !installationLocation.isEmpty()) {
                newProductInstallInfo.setInstallationLocation(installationLocation);
            }

            // 设置现场温度/压力
            String fieldTemperaturePressure = productInstallInfoDto.getFieldTemperaturePressure();
            if (fieldTemperaturePressure != null && !fieldTemperaturePressure.isEmpty()) {
                newProductInstallInfo.setFieldTemperaturePressure(fieldTemperaturePressure);
            }

            // 设置测量介质
            String measurementMedium = productInstallInfoDto.getMeasurementMedium();
            if (measurementMedium != null && !measurementMedium.isEmpty()) {
                newProductInstallInfo.setMeasurementMedium(measurementMedium);
            }

            // 设置自控厂家
            String controlManufacturer = productInstallInfoDto.getControlManufacturer();
            if (controlManufacturer != null && !controlManufacturer.isEmpty()) {
                newProductInstallInfo.setControlManufacturer(controlManufacturer);
            }

            // 前后直管段长度
            String frontAndBackPipeSegment = productInstallInfoDto.getFrontAndBackPipeSegment();
            if (frontAndBackPipeSegment != null && !frontAndBackPipeSegment.isEmpty()) {
                newProductInstallInfo.setFrontAndBackPipeSegment(frontAndBackPipeSegment);
            }

            // 通讯方式
            String communicationMethod = productInstallInfoDto.getCommunicationMethod();
            if (communicationMethod != null && !communicationMethod.isEmpty()) {
                newProductInstallInfo.setCommunicationMethod(communicationMethod);
            }

            // 其他
            String otherNotes = productInstallInfoDto.getOtherNotes();
            if (otherNotes != null && !otherNotes.isEmpty()) {
                newProductInstallInfo.setOtherNotes(otherNotes);
            }

            // 维修人员
            String maintenancePerson = productInstallInfoDto.getMaintenancePerson();
            if (maintenancePerson != null && !maintenancePerson.isEmpty()) {
                newProductInstallInfo.setMaintenancePerson(maintenancePerson);
            }

            // 保修日期
            String warrantyDate = productInstallInfoDto.getWarrantyDate();
            if (warrantyDate != null && !warrantyDate.isEmpty()) {
                newProductInstallInfo.setWarrantyDate(warrantyDate);
            }

            // 服务起止时间
            String servicePeriod = productInstallInfoDto.getServicePeriod();
            if (servicePeriod != null && !servicePeriod.isEmpty()) {
                newProductInstallInfo.setServicePeriod(servicePeriod);
            }

            // 设置任务单ID
            if (confirmationOrder != null && confirmationOrder.getTaskOrderId() != null) {
                newProductInstallInfo.setTaskOrderId(confirmationOrder.getTaskOrderId());
            }


            // 插入新记录
            productInstallInfoMapper.insert(newProductInstallInfo);
        }
        //设置更换零部件表信息
        ReplacementPartDTO[] parts = confirmationOrderDTO.getParts();
        if(parts != null){
            for (ReplacementPartDTO part : parts) {
                if(part.getPartName()== null){
                    continue;
                }
                //序号
                String serialNumber = part.getSerialNumber();
                //数量
                String quantity = part.getQuantity();
                //名称
                String partName = part.getPartName();
                //是否回收
                String isOldPartReturned = part.getIsOldPartReturned();
                //是否过质保
                String isWarrantyValid = part.getIsWarrantyValid();
                //填入更换零部件表
                ReplacementPart replacementPart = new ReplacementPart();
                replacementPart.setProductInstallInfoId(productInstallInfoId);
                replacementPart.setTaskOrderId(confirmationOrder.getTaskOrderId());
                replacementPart.setSerialNumber(serialNumber);
                replacementPart.setPartName(partName);
                replacementPart.setQuantity(quantity);
                replacementPart.setIsOldPartReturned(isOldPartReturned);
                replacementPart.setIsWarrantyValid(isWarrantyValid);
                replacementPartMapper.insert(replacementPart);
            }
        }
        if(confirmationMapper.insert(confirmationOrder)>0){
            aUtils.updateServiceOrderUpdateTime(confirmationOrder.getTaskOrderNumber());
            return ResponseResult.success("确认单添加成功");
        }
        return ResponseResult.error("确认单添加失败");
    }


    /**
     * 更新确认单
     * @param confirmationOrderDTO
     */
    @Override
    @Transactional
    public ResponseResult update(ConfirmationOrderDTO confirmationOrderDTO) {
        //创建实体对象
        ConfirmationOrder confirmationOrder = confirmationMapper.selectById(confirmationOrderDTO.getId());
        //判断当前状态是否都不满足确认发布编辑 还有待完结
        if(!confirmationOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_EDITING)
                && !confirmationOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_CONFIRMED)
                && !confirmationOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_PUBLISHED)
                && !confirmationOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED)
                && !confirmationOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED)){

            log.error("当前状态不能修改");
            return ResponseResult.error("当前状态不能修改");
        }
        //任务编号不允许修改
//        if(confirmationOrder.getTaskOrderNumber()!=confirmationOrderDTO.getTaskOrderNumber()){
//            return ResponseResult.error("任务单编号不能修改");
//        }
        //复制属性目标值在前
        BeanUtils.copyProperties(confirmationOrderDTO,confirmationOrder);
        //根据公司名 联系人名称 联系人电话  查询对应的id
        if(null != confirmationOrderDTO.getCustomerCompanyName())
        confirmationOrder.setCustomerCompanyId(aUtils.getCustomerCompanyId(confirmationOrderDTO.getCustomerCompanyName()));
        if(null != confirmationOrderDTO.getContactPersonName())
        confirmationOrder.setContactPersonId(aUtils.getcontactPersonId(confirmationOrderDTO.getContactPersonName(), confirmationOrderDTO.getContactPersonPhone(), confirmationOrder.getCustomerCompanyId()));
        confirmationOrder.setUpdateTime(LocalDateTime.now());
        confirmationMapper.updateById(confirmationOrder);
        //根据任务单号，获取任务单id
        String orderNumber = confirmationOrderDTO.getTaskOrderNumber();
        Long TaskOrderid = taskorderMapper.selectIdByOrderNumber(orderNumber);

        //更新产品安装信息中间表
        ProductInstallInfoDTO productUseInformationDto = confirmationOrderDTO.getProductUseInformation();
        Long id1=null;
        if(null != productUseInformationDto){
            if(productUseInformationDto.getProductName()== null||productUseInformationDto.getProductName().isEmpty()){
                log.error("产品名称不能为空");
                return ResponseResult.error("产品名称不能为空");
            }
            ProductInstallInfo productInstallInfo = new ProductInstallInfo();
            BeanUtils.copyProperties(productUseInformationDto,productInstallInfo);
            productInstallInfo.setTaskOrderId(TaskOrderid);
            //用1来查询是否能查询的到内容
            LambdaQueryWrapper<ProductInstallInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductInstallInfo::getTaskOrderId, TaskOrderid);
            //先查询是否存在，如果存在则直接更新并赋值id，如果不存在则需要插入
            ProductInstallInfo productInstallInfo1 = deviceInstallInfoMapper.selectOne(queryWrapper);
            //根据名称规格型号查询具体的产品id设置到productInstallInfo中，如果没有则创建
            LambdaQueryWrapper<Product> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Product::getName, productUseInformationDto.getProductName());
            // 校验并添加版本和规格条件
            if (StringUtils.isNotBlank(productUseInformationDto.getVersion())) {
                queryWrapper1.eq(Product::getVersion, productUseInformationDto.getVersion());
            }
            else{
                queryWrapper1.isNull(Product::getVersion);
            }
            if (StringUtils.isNotBlank(productUseInformationDto.getSpecification())) {
                queryWrapper1.eq(Product::getSpecification, productUseInformationDto.getSpecification());
            }
            else{
                queryWrapper1.isNull(Product::getSpecification);
            }
            Product product = productMapper.selectOne(queryWrapper1);
            if(product != null){
                productInstallInfo.setProductId(product.getId());
            }
            else{
                product = new Product();
                product.setName(productUseInformationDto.getProductName());
                product.setVersion(productUseInformationDto.getVersion());
                product.setSpecification(productUseInformationDto.getSpecification());
                productMapper.insert(product);
                productInstallInfo.setProductId(product.getId());
            }
            if (productInstallInfo1 != null) {
                deviceInstallInfoMapper.update(productInstallInfo, queryWrapper);
                id1 = productInstallInfo1.getId();
            }
            else{
                deviceInstallInfoMapper.insert(productInstallInfo);
                id1=productInstallInfo.getId();
            }

        }
        //需要对产品现场信息表和更换零部件表做更新操作
        if(null != confirmationOrderDTO.getParts()){
            replacementPartMapper.deleteByTaskOrderId(TaskOrderid);
        }
        for (ReplacementPartDTO part : confirmationOrderDTO.getParts()) {
            // 创建 ReplacementPart 对象
            ReplacementPart replacementPart = new ReplacementPart();

            // 使用 BeanUtils 复制属性
            BeanUtils.copyProperties(part, replacementPart);

            // 设置外键字段
            replacementPart.setTaskOrderId(TaskOrderid);           // 任务订单 ID
            replacementPart.setProductInstallInfoId(id1);          // 产品安装信息 ID

            // 构建查询条件：根据 taskOrderId 删除旧数据
            LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReplacementPart::getTaskOrderId, TaskOrderid);

            if (part != null) {
                replacementPartMapper.insert(replacementPart);
            }
        }
        aUtils.updateServiceOrderUpdateTime(confirmationOrder.getTaskOrderNumber());
        return ResponseResult.success("更新成功");
    }

    /**
     * 根据任务单id获取确认单
     * @param id
     * @return
     */
    @Override
    public ConfirmationOrderVO getByTaskOrderId(Long id){
        log.info("开始查询任务单id:{}", id);
        LambdaQueryWrapper<ConfirmationOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConfirmationOrder::getId, id);
        ConfirmationOrder confirmationOrder = confirmationMapper.selectOne(queryWrapper);
        ConfirmationOrderVO confirmationOrderVO = new ConfirmationOrderVO();
        BeanUtils.copyProperties(confirmationOrder, confirmationOrderVO);
        String images = confirmationOrder.getImagesUrl();
        //获取图片的预览地址
//        if(images != null && !images.isEmpty()){
//            String presignedUrl = minioService.getPresignedUrl(images);
//            confirmationOrderVO.setImagesUrl(presignedUrl);
//        }
        //查询公司 联系人 联系人电话
        if(confirmationOrder.getCustomerCompanyId() != null)
        confirmationOrderVO.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(confirmationOrder.getCustomerCompanyId()));
        if(confirmationOrder.getContactPersonId() != null)
        confirmationOrderVO.setContactPersonName(aUtils.getContactPersonById(confirmationOrder.getContactPersonId()));
        if(confirmationOrder.getContactPersonId() != null)
        confirmationOrderVO.setContactPersonPhone(aUtils.getPhoneNumberById(confirmationOrder.getContactPersonId()));
        //查询产品安装信息中间表/查询更换零件表
        ProductInstallInfo productInstallInfo = deviceInstallInfoMapper.selectOne(new LambdaQueryWrapper<ProductInstallInfo>().eq(ProductInstallInfo::getTaskOrderId, confirmationOrder.getTaskOrderId()));
        if(productInstallInfo != null){
            ProductInstallInfoVO productInstallInfoVO = new ProductInstallInfoVO();
            BeanUtils.copyProperties(productInstallInfo, productInstallInfoVO);
            //查询产品名称 版本 规格
            Product product = productMapper.selectById(productInstallInfo.getProductId());
            if (product != null) {
                productInstallInfoVO.setProductName(product.getName());
                productInstallInfoVO.setVersion(product.getVersion());
                productInstallInfoVO.setSpecification(product.getSpecification());
            }
            confirmationOrderVO.setProductUseInformation(productInstallInfoVO);
        }
        //查询更换零件表
        List<ReplacementPart> replacementParts = replacementPartMapper.selectList(new LambdaQueryWrapper<ReplacementPart>().eq(ReplacementPart::getTaskOrderId, id));
        if (replacementParts != null){
            ReplacementPartVO[] replacementPartVOS = new ReplacementPartVO[replacementParts.size()];
            for (int i = 0; i < replacementPartVOS.length; i++) {
                ReplacementPart replacementPart = replacementParts.get(i);
                ReplacementPartVO replacementPartVO = new ReplacementPartVO();
                BeanUtils.copyProperties(replacementPart, replacementPartVO);
                replacementPartVOS[i] = replacementPartVO;
            }
            confirmationOrderVO.setParts(replacementPartVOS);
        }
        return confirmationOrderVO;
    }

    @Override
    public ConfirmationOrderVO getByServiceNumber(String orderNumber) {
        log.info("开始查询任务单id:{}", orderNumber);
        LambdaQueryWrapper<ConfirmationOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConfirmationOrder::getTaskOrderNumber, orderNumber)
                .eq(ConfirmationOrder::getIsDeleted, 1);
        ConfirmationOrder confirmationOrder = confirmationMapper.selectOne(queryWrapper);
        if(confirmationOrder == null){
            return null;
        }
        ConfirmationOrderVO confirmationOrderVO = new ConfirmationOrderVO();
        BeanUtils.copyProperties(confirmationOrder, confirmationOrderVO);
        String images = confirmationOrder.getImagesUrl();
        //获取图片的预览地址
//        if(images != null && !images.isEmpty()){
//            String presignedUrl = minioService.getPresignedUrl(images);
//            confirmationOrderVO.setImagesUrl(presignedUrl);
//        }
        //查询公司 联系人 联系人电话
        if(confirmationOrder.getCustomerCompanyId() != null)
            confirmationOrderVO.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(confirmationOrder.getCustomerCompanyId()));
        if(confirmationOrder.getContactPersonId() != null)
            confirmationOrderVO.setContactPersonName(aUtils.getContactPersonById(confirmationOrder.getContactPersonId()));
        if(confirmationOrder.getContactPersonId() != null)
            confirmationOrderVO.setContactPersonPhone(aUtils.getPhoneNumberById(confirmationOrder.getContactPersonId()));
        //查询产品安装信息中间表/查询更换零件表
        ProductInstallInfo productInstallInfo = deviceInstallInfoMapper.selectOne(new LambdaQueryWrapper<ProductInstallInfo>().eq(ProductInstallInfo::getTaskOrderId, confirmationOrder.getTaskOrderId()));
        ProductInstallInfoVO productInstallInfoVO = new ProductInstallInfoVO();
        if(productInstallInfo != null){
            BeanUtils.copyProperties(productInstallInfo, productInstallInfoVO);
            //安装地点
            productInstallInfoVO.setInstallationLocation(productInstallInfo.getInstallationLocation());
            productInstallInfoVO.setInstrumentNumber(productInstallInfo.getInstrumentNumber());
            productInstallInfoVO.setProductPurchaseDate(productInstallInfo.getProductPurchaseDate());
            productInstallInfoVO.setMeasurementMedium(productInstallInfo.getMeasurementMedium());
            productInstallInfoVO.setSafetyLevel(productInstallInfo.getSafetyLevel());
            productInstallInfoVO.setSafetyNotes(productInstallInfo.getSafetyNotes());
            productInstallInfoVO.setCommunicationMethod(productInstallInfo.getCommunicationMethod());
            //查询产品名称 版本 规格
            Product product = productMapper.selectById(productInstallInfo.getProductId());
            if (product != null) {
                productInstallInfoVO.setProductName(product.getName());
                productInstallInfoVO.setVersion(product.getVersion());
                productInstallInfoVO.setSpecification(product.getSpecification());
            }
            confirmationOrderVO.setProductUseInformation(productInstallInfoVO);
        }
        confirmationOrderVO.setProductUseInformation(productInstallInfoVO);
        //查询更换零件表
        List<ReplacementPart> replacementParts = replacementPartMapper.selectListByTaskOrderId(confirmationOrder.getTaskOrderId());
        if (replacementParts != null){
            ReplacementPartVO[] replacementPartVOS = new ReplacementPartVO[replacementParts.size()];
            for (int i = 0; i < replacementPartVOS.length; i++) {
                ReplacementPart replacementPart = replacementParts.get(i);
                ReplacementPartVO replacementPartVO = new ReplacementPartVO();
                BeanUtils.copyProperties(replacementPart, replacementPartVO);
                replacementPartVOS[i] = replacementPartVO;
            }
            confirmationOrderVO.setParts(replacementPartVOS);
        }
        return confirmationOrderVO;
    }

    /**
     * 根据图片更新确认单百度ai
     * @param image
     * @throws IOException
     */
    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();
    @Override
    @Transactional
    public ConfirmationOrderVO updateByImage(MultipartFile image) throws Exception {
        if(image == null){
            throw new Exception("图片不能为空");
        }
        //先上传minio，返回filename，最终返回需要携带filename
        String filename = minioService.uploadFile(image);
            String content =aUtils.getFileContentAsBase64(image, true);
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            // image 可以通过 getFileContentAsBase64("C:\fakepath\123.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            //String content = getFileContentAsBase64("C:\\Users\\Sadie\\Desktop\\12.png", true);
            RequestBody body = RequestBody.create(mediaType, "image="+content);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            //获取返回结果s
            String s = response.body().string();
            System.out.println(s);
            JSONObject jsonObject = new JSONObject(s);
            // 从 tables_result 中获取 body 数组
            JSONArray tablesResult = jsonObject.getJSONArray("tables_result");
            JSONObject firstTable = tablesResult.getJSONObject(0);
            JSONArray body1 = firstTable.getJSONArray("body");

            //定义返回的VO类
            ConfirmationOrderVO confirmationOrderVO= new ConfirmationOrderVO();
            //定义类中类
            ProductInstallInfoVO productInstallInfoVO = new ProductInstallInfoVO();
            //开始提取数据
            String taskId = null;
            // 提取编号
            JSONArray footer = firstTable.getJSONArray("footer");
            // 遍历 body 查找用户名称
            for (int i = 0; i < body1.length(); i++) {
                JSONObject cell = body1.getJSONObject(i);
                //编号
                if ("编号".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setTaskOrderNumber(userName);
                        }
                    }
                }
                //填表人/时间
                if ("填表人/时间".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell, "words");

                            // 👇 增加 null 和空值判断（关键修复）
                            if (userName == null || userName.trim().isEmpty()) {
                                log.warn("填表人/时间 后的单元格内容为空或 null: {}", userCell.toString());
                                // 可选择跳过，或设置默认值
                                continue;
                            }

                            // 使用正则表达式按第一个数字分割
                            String[] parts = userName.trim().split("(?=\\d)", 2);

                            if (parts.length >= 1) {
                                String filler = parts[0].trim(); // 填表人
                                confirmationOrderVO.setFiller(filler);
                            }
                            if (parts.length >= 2) {
                                String fillTime = parts[1].trim(); // 时间
                                confirmationOrderVO.setFillTime(fillTime);
                            }
                        }
                    }
                }
                // 用户名称
                if ("用户名称".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setCustomerCompanyName(userName);
                        }
                    }
                }

                // 地址
                if ("地址".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setAddress(userName);
                        }
                    }
                }

                // 电话
                if ("电话".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            if (userName != null && !userName.trim().isEmpty()) {
                                confirmationOrderVO.setContactPersonPhone(userName);
                                System.out.println("电话: " + userName);
                            }
                        }
                    }
                }
                // 联系人
                if ("联系人".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setContactPersonName(userName);
                        }
                    }
                }

                // 产品购买日期
                if ("产品购买日期".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setProductPurchaseDate(userName);
                        }
                    }
                }
                // 产品名称
                if ("产品名称".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setProductName(userName);
                        }
                    }
                }
                // 型号
                if ("型号".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setVersion(userName);
                        }
                    }
                }
                // 安装地点
                if ("安装地点".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setInstallationLocation(userName);
                        }
                    }
                }
                // 现场温度/压力
                if ("现场\n温度/压力".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setFieldTemperaturePressure(userName);
                        }
                    }
                }
                // 测量介质
                if ("测量介质".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setMeasurementMedium(userName);
                        }
                    }
                }
                // 自控厂家
                if ("自控厂家".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setControlManufacturer(userName);
                        }
                    }
                }
                //前后直管段
                if ("前后直管段".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setFrontAndBackPipeSegment(userName);
                        }
                    }
                }
                //通讯方式
                if ("通讯方式".equals(cell.getString("words"))) {
                        JSONObject userCell = body1.getJSONObject(i + 1);
                        String userName = null;
                        // 判断是否存在 "words" 字段
                        if (!userCell.isNull("words")) {
                            userName = userCell.getString("words");
                        }
                    productInstallInfoVO.setCommunicationMethod(userName);
                }
                //其他
                if ("其他".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setOtherNotes(userName);
                        }
                    }
                }
                //维修人员
                if ("维修人员".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setMaintenancePerson(userName);
                        }
                    }
                }
                //保修日期
                if ("保修日期".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setWarrantyDate(userName == null || userName.trim().isEmpty() ? null : userName.trim());
                        }
                    }
                }
                //服务起止时间
                if ("服务起止时间".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            productInstallInfoVO.setServicePeriod(userName == null || userName.trim().isEmpty() ? null : userName.trim());
                        }
                    }
                }
                //故障现象
                if ("故障现象".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setFaultDescription(userName);
                        }
                    }
                }
                //故障原因\n及处理办法
                if ("故障原因\n及处理办法".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setFaultReasonAndSolution(userName);
                        }
                    }
                }
                //余留问题
                if ("余留问题".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setRemainingIssues(userName);
                        }
                    }
                }
                //用户确认
                if ("用户确认".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setUserConfirmation(userName);
                        }
                    }
                }
                //销售人员确认
                if ("销售人员\n确认".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setSalesmanConfirmation(userName);
                        }
                    }
                }
                //总指挥意见
                if ("总指挥意见".equals(cell.optString("words", null))) {
                    if (i + 1 < body1.length()) {
                        JSONObject userCell = body1.optJSONObject(i + 1);
                        if (userCell != null && !userCell.isNull("words")) {
                            String userName = aUtils.getString(userCell,"words");
                            confirmationOrderVO.setCommanderOpinion(userName);
                        }
                    }
                }
            }


            // 处理“更换零部件”数据
            Map<Integer, Map<String, String>> rowMap = new HashMap<>();
            for (int i = 0; i < body1.length(); i++) {
                JSONObject cell = body1.getJSONObject(i);
                int rowStart = cell.getInt("row_start");
                int colStart = cell.getInt("col_start");
                String words = cell.getString("words").trim();

                if (rowStart >= 12 && rowStart <= 17) {
                    rowMap.putIfAbsent(rowStart, new HashMap<>());
                    switch (colStart) {
                        //case 1: rowMap.get(rowStart).put("序号", words); break;
                        case 2: rowMap.get(rowStart).put("零部件名称", words); break;
                        //case 2: rowMap.get(rowStart).put("规格", words); break;
                        case 3: rowMap.get(rowStart).put("数量", words); break;
                        case 4: rowMap.get(rowStart).put("旧部件是否回收", words); break;
                        case 5: rowMap.get(rowStart).put("是否过质保", words); break;
                        case 6: rowMap.get(rowStart).put("收件人确认", words); break;
                    }
                }
            }

            List<Map<String, String>> partsList = new ArrayList<>();
            for (Map.Entry<Integer, Map<String, String>> entry : rowMap.entrySet()) {
                Map<String, String> row = entry.getValue();
                partsList.add(row);
//                if (entry.getKey() != 12 && row.containsKey("序号") && !row.get("序号").isEmpty()) {
//
//                }
            }
            List<ReplacementPart> replacementParts = new ArrayList<>();
            List<ReplacementPartVO> replacementPartVOList = new ArrayList<>();

            for (Map<String, String> row : partsList) {
                ReplacementPartVO vo = new ReplacementPartVO();
                //vo.setSerialNumber(row.get("序号"));
                vo.setPartName(row.get("零部件名称"));
                vo.setSpecification(row.get("规格"));
                vo.setQuantity(row.get("数量"));
                vo.setIsOldPartReturned(row.get("旧部件是否回收"));
                vo.setIsWarrantyValid(row.get("是否过质保"));
                vo.setRecipientConfirmation(row.get("收件人确认"));
                if(row.size()==0||row.get("零部件名称").equals("零部件名称")||row.get("零部件名称").equals(""))
                    continue;
                replacementPartVOList.add(vo);
            }
            if(partsList.size()==0){
                ReplacementPartVO vo = new ReplacementPartVO();
                replacementPartVOList.add(vo);
            }
            //创建上传图片到minio获取图片的objectName
            String objectName = minioService.uploadFile(image);
            //根据图片objectName获取预签名url存入实体类中
            //String presignedUrl = minioService.getPresignedUrl(objectName);
            confirmationOrderVO.setImagesUrl(objectName);
            confirmationOrderVO.setParts(replacementPartVOList.toArray(new ReplacementPartVO[0]));
            confirmationOrderVO.setProductUseInformation(productInstallInfoVO);
            confirmationOrderVO.setImagesUrl(filename);
            return confirmationOrderVO;
    }

    /**
     * 批量逻辑删除
     * 改变isdelete状态为0
     * @param ids
     */
    @Override
    public boolean batchDelete(String[] ids) {
        //存入回收站
        RecycleBinOrder recycleBinOrder = new RecycleBinOrder();
        for (String id : ids) {
            ConfirmationOrder confirmationOrder = confirmationMapper.selectById(id);
            //查询是否包含后置订单
            if(taskorderMapper.selectByTaskOrderNumber(confirmationOrder.getTaskOrderNumber())){
                log.error("该售后问题下有订单数据，不允许删除！");
                return false;
            }
            //删除对应的更换零件表
            LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReplacementPart::getTaskOrderId,confirmationOrder.getTaskOrderId());
            replacementPartMapper.delete(wrapper);
            recycleBinOrder.setOrderNumber(confirmationOrder.getTaskOrderNumber());
            recycleBinOrder.setOrderType(Status.CONFIRMATION_ORDER);
            recycleBinOrder.setDeletedBy(SecurityUtils.getCurrentUsername());
            recycleBinOrder.setOrderId(confirmationOrder.getId());
            recycleBinOrder.setCustomerName(aUtils.getCustomerCompanyNameById(confirmationOrder.getCustomerCompanyId()));
            recyclebinMapper.insert(recycleBinOrder);
            confirmationOrder.setIsDeleted(0);
            try {
                confirmationMapper.updateById(confirmationOrder);
            } catch (Exception e) {
                System.err.println(id+"删除失败");
            }
        }
        return true;
    }

    /**
     * 条件分页查询
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param customerName 公司名称
     * @param taskOrderNumber 订单编号
     * @param startTime 产品购买日期开始时间
     * @param endTime 产品购买日期结束时间
     * @param status 状态
     * @return
     */
    @Override
    public IPage<ConfirmationOrderVO> getByPage(Integer pageNum,
                                                Integer pageSize,
                                                String customerName,
                                                String taskOrderNumber,
                                                String startTime,
                                                String endTime,
                                                Integer status) {

        // 处理分页参数
        Page<ConfirmationOrderVO> page;
        if (pageSize == null) {
            // 查询全部数据，使用足够大的页面大小
            page = new Page<>(1, 100000);
        } else {
            // 正常分页
            page = new Page<>(pageNum, pageSize);
        }

        IPage<ConfirmationOrderVO> resultPage = confirmationMapper.getConfirmationOrdersByPage(page, customerName, taskOrderNumber, endTime, endTime, status);

        List<ConfirmationOrderVO> voList = resultPage.getRecords();

        // 缓存 taskOrderNumber -> taskId，避免重复调用 aUtils
        Map<String, Long> taskOrderNumberToTaskIdMap = new HashMap<>();

        if (!voList.isEmpty()) {
            for (ConfirmationOrderVO vo : voList) {
                String currentTaskOrderNumber = vo.getTaskOrderNumber();

                // 从缓存中获取 taskId
                Long taskId = taskOrderNumberToTaskIdMap.get(currentTaskOrderNumber);

                // 如果缓存中没有，调用工具类获取并缓存
                if (taskId == null && StringUtils.isNotBlank(currentTaskOrderNumber)) {
                    taskId = aUtils.getTaskOrderIdByServiceNumber(currentTaskOrderNumber);
                    taskOrderNumberToTaskIdMap.put(currentTaskOrderNumber, taskId);
                }

                if (taskId != null) {
                    // 查询替换件列表
                    LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(ReplacementPart::getTaskOrderId, taskId)
                            .eq(ReplacementPart::getStatus, "2");

                    List<ReplacementPart> replacementPartList = replacementPartMapper.selectList(wrapper);

                    List<ReplacementPartVO> replacementPartVOList = new ArrayList<>();
                    if (replacementPartList != null && !replacementPartList.isEmpty()) {
                        for (ReplacementPart part : replacementPartList) {
                            ReplacementPartVO partVO = new ReplacementPartVO();
                            BeanUtils.copyProperties(partVO, part); // 注意参数顺序：目标在前
                            replacementPartVOList.add(partVO);
                        }
                    }

                    vo.setParts(replacementPartVOList.toArray(new ReplacementPartVO[0]));
                } else {
                    vo.setParts(new ReplacementPartVO[0]);
                }
            }
        }

        // 如果是查询全部，调整分页信息
        if (pageSize == null) {
            resultPage.setPages(1);
            resultPage.setCurrent(1);
            resultPage.setSize(resultPage.getTotal());
        }

        return resultPage;
    }



    /**
     * 工厂方法 恢复工单状态
     * @param orderId
     * @return
     */
    @Override
    public boolean restoreOrderById(Long orderId) {
        //设置isdelete为1 恢复数据
        ConfirmationOrder confirmationOrder = new ConfirmationOrder();
        confirmationOrder.setIsDeleted(1);
        return confirmationMapper.update(confirmationOrder, new LambdaQueryWrapper<ConfirmationOrder>().eq(ConfirmationOrder::getId, orderId)) > 0;
    }

    /**
     * 彻底删除工单
     * @param orderId
     * @return
     */
    @Override
    public boolean deleteOrderById(Long orderId) {
        return confirmationMapper.deleteById(orderId) > 0;
    }

@Autowired
private ServiceSummaryOrderService serviceSummaryOrderService;

    /**
     * 工单状态更新，确认单改变状态为由进行中改为完结态
     * 待总结态推送到待完结态
     * @param confirmationOrderDTO
     */
    @Override
    public void updateStatus(ConfirmationOrderDTO confirmationOrderDTO) {
        //获取任务单id和状态
        String status = confirmationOrderDTO.getStatus();
        Long id = confirmationOrderDTO.getId();
        //待总结-转待完结
        if(status.equals(Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED))
        {
            //创建要发生的消息?不太需要发发送，因为确认单和总结单的处理时间可能是一致的，在总结单发审核消息就行
            ConfirmationOrder confirmationOrder = confirmationMapper.selectById(id);
            ServiceSummaryOrder serviceSummaryOrder = new ServiceSummaryOrder();
            //设置售后编号
            serviceSummaryOrder.setServiceNumber(confirmationOrder.getTaskOrderNumber());
            //设置公司id，联系人id
            serviceSummaryOrder.setCustomerCompanyId(confirmationOrder.getCustomerCompanyId());
            serviceSummaryOrder.setCustomerContactsId(confirmationOrder.getContactPersonId());
            //设置地址
            serviceSummaryOrder.setServiceLocation(confirmationOrder.getAddress());
            //查询对应的销售经理id吗，根据售后编号去通知单中获取
            LambdaQueryWrapper<ServiceOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ServiceOrder::getServiceOrderNumber, confirmationOrder.getTaskOrderNumber())
                    .eq(ServiceOrder::getIsDeleted, "1");
            ServiceOrder serviceOrder = serviceOrderMapper.selectOne(wrapper);
            if(serviceOrder != null) {
                Long salesManagerId = serviceOrder.getSalesManagerId();
                serviceSummaryOrder.setSalesManagerId(salesManagerId);
            }
            //根据售后编号查询对应的任务单id,用于后续查询对应的更换零件表
            Long taskId = aUtils.getTaskOrderIdByServiceNumber(confirmationOrder.getTaskOrderNumber());
            serviceSummaryOrder.setTaskId(taskId);
            //设置状态为待完结状态
            serviceSummaryOrder.setStatus(Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED);
            serviceSummaryOrder.setCreatedBy(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
            //创建新的总结单
            serviceSummaryOrderMapper.insert(serviceSummaryOrder);
            //设置当前确认单的状态为待完结
            confirmationOrder.setStatus(Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED);
            confirmationMapper.updateById(confirmationOrder);
            //设置总括表的状态同步为待完结
            LambdaQueryWrapper<AfterSales> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(AfterSales::getOrderNumber, confirmationOrder.getTaskOrderNumber());
            AfterSales afterSales = afterSalesMapper.selectOne(wrapper1);
            afterSales.setStatus(Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED);
            afterSalesMapper.updateById(afterSales);
            //设置通知单 任务单状态同步为待完结
            //设置任务表同步为已完结
            taskorderMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED);
            //设置通知单同步为已完结
            serviceOrderMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_COMPLETED);

        }
    }
}
